<template>
  <div class="login">
    <el-form
      :model="loginForm"
      :rules="rules"
      label-width="100px"
      ref="loginForm"
      class="form"
    >
      <h1 class="title">个人博客管理系统</h1>
      <el-form-item label="用户" prop="username">
        <el-input
          v-model="loginForm.username"
          placeholder="请输入用户名"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button class="but" type="primary" @click="submitForm('loginForm')"
          >登录</el-button
        >
        <el-button class="but" @click="register">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { login } from "../api/login";
import { ElMessage } from "element-plus";
export default {
  name: "Login",
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { message: "请输入用户名称", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        password: [{ message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm(formName) {
      console.log(formName);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.loginForm);
          login(this.loginForm.username, this.loginForm.password).then(
            (res) => {
              if (res.code == 200) {
                this.$store.commit("SET_USERINFO", res.data);
                this.$store.commit("SET_UPDATEAVATARURL", res.data.avatar);
                sessionStorage.setItem("userInfo", JSON.stringify(res.data));
                //this.$store.commit("SET_ISLOGIN", false);
                this.$router.push("/");
                ElMessage.success("登录成功");
              } else {
                ElMessage.error(res.msg);
              }
            }
          );
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    register() {
      this.$router.push("/register");
    },
  },
};
</script>
<style lang="less" scoped>
.login {
  width: 100%;
  height: 100vh;
  background: url(../assets/login-bg.png) no-repeat fixed center !important;
  background-size: 100% 100% !important; /**拉伸图片 */
  .form {
    width: 400px;
    text-align: center;
    margin: 0 auto;
    padding: 1%;
    background: #ffffff;
    position: relative;
    top: 30%;
    border-radius: 10px;
    .title {
      font-size: 20px;
    }
    .but {
      margin: 0 auto;
    }
  }
}
</style>
